package com.example.myapplication3.home;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;

import com.example.myapplication3.R;


/**
 * 自定义组合布局
 *
 * @author yuanc
 * @Description: (用一句话描述)
 * @date 2025/8/9 16:34
 */
public class CardItem extends CardView {

    public CardItem(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, android.R.attr.calendarViewStyle);
    }

    public CardItem(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        // 获取xml属性, 自定义属性在 attrs.xml 中定义
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.cardItem);
        String title = ta.getString(R.styleable.cardItem_myCardItemTitle);
        int icon = ta.getResourceId(R.styleable.cardItem_myCardItemIcon, -1);
        ta.recycle();
        // 将自定义xml布局设定给当前视图,注意 root为this, attachToRoot为true
        LayoutInflater.from(context).inflate(R.layout.layout_home_item, this, true);
        ImageView iv_icon = findViewById(R.id.iv_icon);
        TextView tv_title = findViewById(R.id.iv_title);
        // 根据xml属性值，更新数据
        tv_title.setText(title);
        iv_icon.setImageResource(icon);
    }
}
